package com.petecat.interchan.base.warning.empl.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.mhuang.common.util.DataUtils;
import com.petecat.interchan.base.project.service.IProjectService;
import com.petecat.interchan.base.syscustom.entity.SysUserProject;
import com.petecat.interchan.base.syscustom.mapper.ICustomMapper;
import com.petecat.interchan.base.util.ExeclOutFile;
import com.petecat.interchan.base.warning.config.service.IWarningConfigService;
import com.petecat.interchan.base.warning.empl.entity.BsWarningEmpl;
import com.petecat.interchan.base.warning.empl.mapper.IWarningEmplMapper;
import com.petecat.interchan.base.warning.empl.service.IWarningEmplService;
import com.petecat.interchan.base.warning.rule.entity.BsWarningRule;
import com.petecat.interchan.base.warning.rule.service.IWarningRuleService;
import com.petecat.interchan.core.service.impl.BaseServiceImpl;
import com.petecat.interchan.protocol.base.config.dto.BsWarningConfigQryDTO;
import com.petecat.interchan.protocol.base.config.dto.DelEmplDTO;
import com.petecat.interchan.protocol.base.config.vo.BsWarningConfigTreeVO;
import com.petecat.interchan.protocol.base.empl.dto.BsWarningEmplQryDTO;
import com.petecat.interchan.protocol.base.empl.vo.BsWarningEmplTreeVO;
import com.petecat.interchan.protocol.base.rule.dto.BsWarningRuleAddDTO;
import com.petecat.interchan.protocol.data.PageVO;
import com.petecat.interchan.protocol.sso.company.vo.SysCompanyQryVO;
import com.petecat.interchan.protocol.sso.companyempl.dto.BsSmsAddDTO;
import com.petecat.interchan.redis.commands.IRedisExtCommands;

@Service
public class WarningEmplServiceImpl extends BaseServiceImpl<BsWarningEmpl, String> implements IWarningEmplService {
	
	@Autowired
	private IWarningEmplMapper warningEmplMapper;

	@Autowired
	private IRedisExtCommands redisExtCommands;
	
	@Autowired
	private ICustomMapper customMapper;
	
	private final static Integer ZERO=0;
	
	private final static String SYS_COMPANY_USER_PREKEY="sys_company_user";
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveWarningEmpl(BsWarningRuleAddDTO bsWarningRuleAddDTO, String userId) {
		BsWarningEmpl config = DataUtils.copyTo(bsWarningRuleAddDTO, BsWarningEmpl.class);
		this.warningEmplMapper.save(config);
	}

	
	/**
	 * TREE查询预警人员
	 */
	@Override
	public PageVO<BsWarningEmplTreeVO> queryWarningEmplTree(BsWarningEmplQryDTO bsWarning) {
		List<BsWarningEmplTreeVO> treeVO = this.warningEmplMapper.queryWarningRuleTree(bsWarning);
		PageVO<BsWarningEmplTreeVO>  page = new PageVO<BsWarningEmplTreeVO>();
		if(!treeVO.isEmpty()) {
			for (BsWarningEmplTreeVO bsWarningEmplTreeVO : treeVO) {
				bsWarningEmplTreeVO.setUserName(redisExtCommands.hget(ZERO, SYS_COMPANY_USER_PREKEY, bsWarningEmplTreeVO.getEmplUserId(), SysCompanyQryVO.class).getName());;
			}
			page.setResult(treeVO);
		}
		return page;
	}

	
	/**
	 * 通过规则ID获取预警人员
	 */
	@Override
	public List<BsWarningEmpl> queryEmplListByRuleId(String ruleId) {
		List<BsWarningEmpl> ruleList = this.warningEmplMapper.queryEmplListByRuleId(ruleId);
		if(!ruleList.isEmpty()) {
			return ruleList;
		}
		return null;
	}


	/**
	 * 通过RuleId和UserId删除多个预警人员 
	 */
	@Override
	public void delEmplsByUserIdAndRuleId(List<DelEmplDTO> delEmplDTO) {
		this.warningEmplMapper.delEmplsByUserIdAndRuleId(delEmplDTO);
	}

	
	/**
	 * 删除所有预警人员
	 */
	@Override
	public void delEmplsByRuleId(String id) {
		this.warningEmplMapper.delEmplsByRuleId(id);
	}

	
	/**
	 * 删除规则对应的表中残余多余预警人员
	 */
	@Override
	public void delEmplsByRuleIds(String[] delRules) {
		this.warningEmplMapper.delEmplsByRuleIds(delRules);
	}
	@Autowired
	private IProjectService projectService;
	@Autowired
	private IWarningConfigService warningConfigService; 
	@Autowired
	private IWarningRuleService warningRuleService;
	@Autowired
	private IWarningEmplService warningEmplService;
	
	private final static String SYUSER_REDIS_USERID_TO_USER_PREKEY="syur_user_uid_";
	
	private final static String userNotExites = "user_not_exites";

	private final static String BS_EWARNING="bs_ewarning";
	
	@Autowired
	private Environment environment;
	/**
	 * 导出每个项目启动规则的预警人员信息到Excel
	 */
	@Override
	public ResponseEntity<byte[]> outOpenRuleEmplInfo(String userId) {
		//根据当前用户ID查询出所有项目ID
		List<SysUserProject> userProject = customMapper.findUserProjectByUserId(userId);
		//通过项目ID查询项目名称
		String projectName = "";
		JSONArray head = new JSONArray();
		List<JSONArray> jsonList = null;
		JSONArray body = null;
		List<BsWarningConfigTreeVO> configList = null;
		List<BsWarningRule> ruleList = null;
		List<BsWarningEmpl> emplList = null;
		ResponseEntity<byte[]> returnFile = null;
		ByteArrayOutputStream outputStream = null;
		Integer indexNumber = 0;
		String isSms = "";
		String isEmail = "";
		String status = "";
		String ruleType = "";
		String text = "";
		String [] hea = new String[]{"所属规则租名称","所属规则类型","人员姓名","联系电话","邮箱地址","短信权限","邮箱权限","状态"};
		head = new JSONArray(Arrays.asList(hea));
		//创建一个excel工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //循环创建 一个项目一个Sheet页面
		for (SysUserProject sysUserProject : userProject) {
			projectName = projectService.getNameByProjectId(sysUserProject.getProjectId());
			jsonList = new ArrayList<>();
			//通过项目ID去查找所有的规则信息
			BsWarningConfigQryDTO dto = new BsWarningConfigQryDTO();
			dto.setProjectId(sysUserProject.getProjectId());
			dto.setUserId(userId);
			//查询出所有的config规则组信息
			configList = warningConfigService.queryWarningConfigTree(dto).getResult();
			//通过规则组ID信息去查找到所有规则和人员信息和权限
			for (BsWarningConfigTreeVO config : configList) {
				//获取规则List
				ruleList = warningRuleService.queryWarningListById(config.getConfigId());
				if(!ruleList.isEmpty()){
					for (BsWarningRule rule : ruleList) {
						body = new JSONArray();
						//设置规则组COnfig名称
						body.add(config.getConfigName());
						//设置规则类型
						ruleType = rule.getType();
						if("0".equals(ruleType)){
            				text = "服务器信息";
            			}else if("1".equals(ruleType)){
            				text = "硬件";
            			}else if("2".equals(ruleType)){
            				text = "软件";
            			}else if("3".equals(ruleType)){
            				text = "应用";
            			}else if("4".equals(ruleType)){
            				text = "服务器状态";
            			}else if("5".equals(ruleType)){
            				text = "其他";
            			}else if("6".equals(ruleType)){
            				text = "串口";
            			}
						body.add(text);
						emplList = warningEmplService.queryEmplListByRuleId(rule.getId());
						if(null != emplList) {
							for (BsWarningEmpl d : emplList) {
								//获取到用户信息
								BsSmsAddDTO hget = redisExtCommands.hget(ZERO,SYS_COMPANY_USER_PREKEY, d.getUserId(), BsSmsAddDTO.class);
								body.add(hget.getName());
								body.add(hget.getSms());
								isEmail = "1".equals(d.getIsEmail())?"有权限":"无权限";
								isSms = "1".equals(d.getIsSms())?"有权限":"无权限";
								status = "1".equals(hget.getStatus())?"启用":"停用";
								body.add(hget.getEmail());
								body.add(isSms);
								body.add(isEmail);
								body.add(status);
								
							}
						}
						jsonList.add(body);
					}
				}
			}
			//每次都创建一个sheet 最后全部都出来了
			HSSFWorkbook expExcel = ExeclOutFile.expExcel(workbook,head, jsonList, projectName,indexNumber);
			//创建一个字节数组输出流对象
	        outputStream = new ByteArrayOutputStream();
	        try {
				expExcel.write(outputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}  
	        indexNumber++;
		}

		
		try {
				
	        HttpHeaders headers=new HttpHeaders();
	        String fileName=new String("预警人员信息.xls".getBytes("UTF-8"),"iso-8859-1");
	        headers.setContentDispositionFormData("attachment", fileName);
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		    returnFile=new ResponseEntity<byte[]>
		                            (outputStream.toByteArray(),headers,HttpStatus.CREATED);
		    outputStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		return returnFile;
	}

}
